# 高德路径规划借口，写好起点和终点经纬度，生成轨迹点上传的json测试数据
import time
import requests
import json

# 高德地图API的接口地址  路径规划
url = "https://restapi.amap.com/v3/direction/driving"

# 起点和终点的经纬度
origin = "87.74147,43.847202"
destination = "87.705665,43.852232"

# 保存 postman 测试数据
postman_dic = {
        "carId": 4,  # 车辆id,填写自己测试数据对应车辆
        "points": []
    }

# 保存前端模拟行程测试数据
data_list = []

# 高德地图开放平台申请的密钥
key = "51ed8325b70851604c3342662e117aa2"

# 发送GET请求，获取导航路线
response = requests.get(url, params={
    "origin": origin,
    "destination": destination,
    "key": key
})

# 解析返回的JSON数据
result = response.json()
# print(result)
trajectory = []
if result["status"] == "1" and result["count"] != "0":
    # 获取导航路线的轨迹点坐标
    steps = result["route"]["paths"][0]["steps"]
    for step in steps:
        trajectory.extend(step["polyline"].split(";"))
    # print(trajectory)
else:
    print("获取导航路线失败")

if trajectory:
    # 构造要求的格式
    start_time = int(time.time() * 1000)  # 毫秒
    end_time = start_time + 2 * 60 * 1000  # 行使2分钟
    time_interval = (end_time - start_time) / len(trajectory)
    current_time = start_time
    for point in trajectory:
        data_list.append({
            "location": point
        })
        postman_dic["points"].append({
            "location": point,
            "locatetime": int(current_time)
        })
        current_time += time_interval

    postman_jsonStr = json.dumps(postman_dic)
    data_jsonStr = json.dumps(data_list)

    # # 生成前端模拟行程测试数据
    # print(data_jsonStr)
    # # 生成 postman 测试数据
    # print(postman_jsonStr)

    # 将postman_jsonStr写入postman.json文件
    with open("postman.json", "w") as postman_file:
        postman_file.write(postman_jsonStr)

    # 将data_jsonStr写入data.json文件
    with open("data.js", "w") as data_file:
        data_file.write("export const data = ")
        data_file.write(data_jsonStr)

    print("数据构造成功！")
